﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR_WPF.TranslateHelper
{
    public class TengXunTranslate : ITranslate
    {
        // 腾讯云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId;
        // 腾讯云中开通对应服务应用的 Secret Key
        private static String clientSecret;

        static TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        Int64 currentTime = Convert.ToInt64(ts.TotalSeconds);
        public TengXunTranslate()
        {
            clientId = ConfigurationManager.AppSettings["Tengxun_Id"];
            clientSecret = ConfigurationManager.AppSettings["Tengxun_Key"];
        }
        public string SendContent(string content)
        {
            string authHost = "https://tmt.tencentcloudapi.com/";
            RestClient restClient = new RestClient(authHost);
            RestRequest restRequest = new RestRequest(Method.POST);

            restRequest.AddHeader("host", "tmt.tencentcloudapi.com");
            restRequest.AddParameter("Action", "TextTranslate");//
            restRequest.AddParameter("Version", "2018-03-21");
            restRequest.AddParameter("Region", "ap-guangzhou");//
            restRequest.AddParameter("Timestamp", currentTime);//
            restRequest.AddParameter("Nonce", "1223455");//
            restRequest.AddParameter("SecretId", clientId);//

            restRequest.AddParameter("Signature", getSign(content));
            restRequest.AddParameter("SourceText", content);//
            restRequest.AddParameter("Source", "auto");//
            restRequest.AddParameter("Target", "zh");//
            restRequest.AddParameter("ProjectId", "0");//

            var result = restClient.Execute(restRequest);

            try
            {
                var lst = new List<string>();
                dynamic json = JsonConvert.DeserializeObject(result.Content);
                return string.Join("\r\n\r\n    ", json.Response.TargetText.ToString());
            }
            catch (Exception)
            {
                return "出现了点小问题";
            }
        }

        protected string getSign(string q)
        {
            string sign = string.Format("POSTtmt.tencentcloudapi.com/?Action={0}&Nonce={1}&ProjectId={2}" +
                "&Region={3}&SecretId={4}&Source={5}&SourceText={6}&Target={7}&Timestamp={8}&Version={9}", "TextTranslate",
                "1223455", "0", "ap-guangzhou", clientId, "auto", q, "zh", currentTime, "2018-03-21");

            var enc = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(clientSecret));
            hmac.Initialize();

            byte[] buffer = enc.GetBytes(sign);
            return Convert.ToBase64String(hmac.ComputeHash(buffer));
        }
    }
}
